var express = require('express');
var app = express();  // 引入express模块
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.use('/', express.static(__dirname + '/www'));


app.get('/', function(req, res){  // 路由为localhost:3000时向客户端响应“hello world”
  res.send('<h3>Hello world</h3>');  // 发送数据
});


let users = [];
let userInfo = [];

io.on('connection', (socket) => {
    console.log('connection success...');
    socket.emit('connection', { data: 'success' });
    socket.emit('showUser', userInfo);
    socket.on('login', res => {     
        if (users.includes(res.name) ) {
            socket.emit('login', { data:400});
        } else {
            socket.emit('login', { data: 200 });
            users.push(res.name);
            userInfo.push(res);
            console.log(userInfo,55555555)
            io.emit('showUser', userInfo);
            io.emit('system', {
                name: res.name,
                status: '进入'
            });
        }
    })
    
})
// 断开连接时
io.on('disconnect', ()=> {
    var index = users.indexOf(socket.nickname); 
    if(index > -1 ) {  // 避免是undefined
        users.splice(index, 1);  // 删除用户信息
        usersInfo.splice(index, 1);  // 删除用户信息

        io.emit('system', {  // 系统通知
            name: socket.nickname,
            status: '离开'
        });
        
        io.emit('disUser', usersInfo);  // 重新渲染
        console.log('a user left.');
    }
});

http.listen(3000, function(){  // 监听3000端口
  console.log('listening success 3000.....'); 
}); 

